using System;
using System.Collections.Generic;
using System.Text;

namespace RapidHDL
{
    public static class IOMemoryTest
    {

        public static void TestMemory(int piStart, int piMax)
        {
            const int BLOCKS = 4;
            const int cOffset = 100;
            const uint cTest = 0xAAAAAAAA;

            MemoryBlock oMemoryBlock = new MemoryBlock();

            for (int iAddress = piStart; iAddress < piMax; iAddress++)
            {
                if (oMemoryBlock.MemoryList.Count == 4)
                {
                    if (!IOInterface.PostMemory(ref oMemoryBlock))
                    {
                        oMemoryBlock.DebugDisplay();
                    }
                    oMemoryBlock.Reset();
                }
                oMemoryBlock.WriteMemory(iAddress, (uint)cTest);
            }


            for (int iAddress = piStart; iAddress < piMax; iAddress++)
            {
                if (oMemoryBlock.MemoryList.Count == 4)
                {
                    if (!IOInterface.PostMemory(ref oMemoryBlock))
                    {
                        oMemoryBlock.DebugDisplay();
                    }
                    oMemoryBlock.Reset();
                }
                oMemoryBlock.WriteMemory(iAddress, (uint)cTest);
            }


            if (oMemoryBlock.MemoryList.Count > 0)
                IOInterface.PostMemory(ref oMemoryBlock);

            bool bError = false;
            int iLastError = 0;
            for (int iAddress = piStart; iAddress < piMax; iAddress++)
            {
                oMemoryBlock.Reset();
                oMemoryBlock.RequestMemory(iAddress);
                if (!IOInterface.PostMemory(ref oMemoryBlock))
                {
                    oMemoryBlock.DebugDisplay();
                }
                if (oMemoryBlock.ReturnMemory(iAddress) != cTest)
                {
                    if (!bError)
                    {
                        iLastError = iAddress;
                        bError = true;
                    }
                }
                else
                {
                    if (bError)
                    {
                        int iErrorEnd = iAddress - 1;
                        string sReport = "BAD MEM: " + iLastError.ToString() + " to " + iErrorEnd.ToString();
                        Console.WriteLine(sReport);
                        bError = false;
                    }
                }
            }

            if (bError)
            {
                int iErrorEnd = piMax;
                string sReport = "BAD MEM: " + iLastError.ToString() + " to " + iErrorEnd.ToString();
                Console.WriteLine(sReport);
                bError = false;
            }
            Console.WriteLine("FINISHED--------------");

        }
    }
}
